<?php

namespace app\common\controller;

use app\api\model\Member;
use app\exceptions\ApiException;
use think\App;
use think\facade\Config;
use think\facade\Request;
use Throwable;
use think\facade\Event;
use app\common\library\Auth;
use think\exception\HttpResponseException;
use app\common\library\token\TokenExpirationException;

class Frontend extends Api
{
    /**
     * 无需登录的方法
     * 访问本控制器的此方法，无需会员登录
     * @var array
     */
    protected array $noNeedLogin = [];

    /**
     * 可登录可不登录方法
     * 访问本控制器的此方法，无需会员登录
     * @var array
     */

    protected array $needOrNoLogin = [];


    /**
     * 无需鉴权的方法
     * @var array
     */
    protected array $noNeedPermission = [];


    protected $request_array = [];

    /**
     * 权限类实例
     * @var Auth
     */
    protected Auth $auth;


    /**
     * 构造方法
     * @access public
     *
     * @param Request $request Request 对象
     */
    public function __construct(App $app)
    {
        $this->request = is_null($app->request) ? \think\facade\Request::instance() : $app->request;
        $this->request_array = $app->request->param();
        // 控制器初始化
        $this->_initialize();
    }


    /**
     * 初始化
     * @throws Throwable
     * @throws HttpResponseException
     */
    protected function _initialize()
    {
        $this->request_array = $this->request->param();
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        $authorization = request()->header('authorization');
        $token = trim(str_ireplace('Bearer', '', $authorization));
        // 检测是否需要验证登录
        if ((!$this->match($this->noNeedLogin) && !$this->match($this->needOrNoLogin)) || ($this->match($this->needOrNoLogin) && $token) ) {
            //校验登录状态
            if (!$token) {
                throw  new ApiException('未登录,请前往个人中心登录', 401);
            }
            $check_result = (new \app\common\model\Token())->check_token($token, $act_type = 1);

            $this->request_array['member_id'] = $check_result['member_id'];
            //查询状态
            $user = (new Member())->where(['id' => $check_result['member_id']])->find();
            if (empty($user)) {
                throw  new ApiException('用户不存在', 401);
            }
            if ($user && $user['status'] == 0 && $user['expire_time'] > time()) {
                $expire_time = $this->timeDifference($user['expire_time']);
                throw  new ApiException('您的账号已被冻结,剩余时长:'.$expire_time, 401);
            }
        }
    }


    public function timeDifference($timestamp) {
        // 获取当前时间戳
        $currentTimestamp = time();
        // 计算时间差，单位秒
        $diff = $currentTimestamp - $timestamp;
        // 计算天数
        $days = floor($diff / (60 * 60 * 24));
        $diff -= $days * (60 * 60 * 24);
        // 计算小时数
        $hours = floor($diff / (60 * 60));
        $diff -= $hours * (60 * 60);
        // 计算分钟数
        $minutes = floor($diff / 60);
        $diff -= $minutes * 60;
        // 计算秒数
        $seconds = $diff;
        // 构造返回值
        $result = '';
        if ($days > 0) {
            $result .= $days . "天 ";
        }
        if ($hours > 0) {
            $result .= $hours . "小时 ";
        }
        if ($minutes > 0) {
            $result .= $minutes . "分钟 ";
        }
        if ($seconds > 0) {
            $result .= $seconds . "秒";
        }

        return $result;
    }




    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return false;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }
}